class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}



public class Solution92 {

    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode ptr=head;
        ListNode first;
        ListNode firstTail=null;
        if(left==1){
            first=null;
        }
        else{
            first=head;
        }
        ListNode mid=null;
        ListNode last=null;
        ListNode nextPtr=null;
        int count=1;
        while(ptr!=null){
            nextPtr=ptr.next;
            if(count==left-1){
                firstTail=ptr;
                mid=ptr.next;
                ptr.next=null;
            }
            if(count==left&&mid==null){
                mid=ptr;
            }
            if(count==right){
                last=ptr.next;
                ptr.next=null;
            }
            count++;
            ptr=nextPtr;
        }

        ptr=mid;
        ListNode midHead=null;
        ListNode midTail=null;
        while(ptr!=null){
            if(midHead==null&&midTail==null){
                midHead=ptr;
                midTail=ptr;
                ptr=ptr.next;
                continue;
            }
            nextPtr=ptr.next;
            ptr.next=midHead;
            midHead=ptr;
            ptr=nextPtr;
        }
        ListNode newHead=null;
        if(midTail!=null) {
            midTail.next = last;
            newHead=midHead;
        }
        if(first!=null) {
            firstTail.next = midHead;
            newHead=first;
        }
        return newHead;
    }
}
